<template>
  <div class="weekly-calendar">
    <div class="calendar-controls">
      <div class="week-navigation">
        <button class="nav-btn" @click="previousWeek">
          <span class="arrow">←</span> 上一周
        </button>
        <div class="current-week">
          {{ formatWeekRange(currentWeekStart) }}
        </div>
        <button class="nav-btn" @click="nextWeek">
          下一周 <span class="arrow">→</span>
        </button>
      </div>
    </div>

    <div class="calendar-header">
      <div class="time-column"></div>
      <div v-for="day in weekDays" :key="day.date" class="day-column">
        <div class="day-header">
          <div class="day-name">{{ day.name }}</div>
          <div class="day-date">{{ formatDate(day.date) }}</div>
        </div>
      </div>
    </div>
    
    <div class="calendar-body">
      <div class="time-slots">
        <div v-for="hour in 24" :key="hour" class="time-slot">
          <div class="time-label">{{ formatHour(hour - 1) }}</div>
        </div>
      </div>
      
      <div class="days-grid">
        <div v-for="day in weekDays" :key="day.date" class="day-column">
          <div v-for="hour in 24" :key="hour" class="time-slot">
            <template v-for="event in getVisibleEvents(day.date, hour - 1)" :key="event.id">
              <div class="event"
                   :style="getEventStyle(event, hour - 1)"
                   @click="showEventDetails(event)">
                <span v-if="!isShortEvent(event)">{{ event.scheduleName }}</span>
              </div>
            </template>
          </div>
        </div>
      </div>
    </div>

    <!-- 事件详情弹窗 -->
    <Teleport to="body">
      <Transition name="modal">
        <div v-if="selectedEvent" class="modal-overlay" @click="closeEventDetails">
          <div class="modal-content" @click.stop>
            <div class="modal-header" :style="{ backgroundColor: getColorByFeeling(selectedEvent) }">
              <h2>{{ selectedEvent.scheduleName }}</h2>
              <button class="close-btn" @click="closeEventDetails">×</button>
            </div>
            <div class="modal-body">
              <div class="event-info">
                <div class="info-item">
                  <i class="icon">📅</i>
                  <span>{{ formatDate(selectedEvent.date) }}</span>
                </div>
                <div class="info-item">
                  <i class="icon">⏰</i>
                  <span>{{ formatTimeDisplay(selectedEvent.createTime) }} - {{ formatTimeDisplay(selectedEvent.endTime) }}</span>
                </div>
                <div class="info-item">
                  <i class="icon">🕒</i>
                  <span>{{ calculateDuration(selectedEvent) }}</span>
                </div>
                <div class="info-item">
                  <i class="icon">😊</i>
                  <span>心情指数：{{ selectedEvent.feeling }}</span>
                </div>
              </div>
              <div class="event-description">
                <h3>日程详情</h3>
                <p>{{ selectedEvent.description || '暂无详细描述' }}</p>
              </div>
            </div>
          </div>
        </div>
      </Transition>
    </Teleport>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import {
  getReverseList
} from "@/api/schedule";

// 当前周的起始日期
const currentWeekStart = ref(new Date())
const startDate = ref('')
const endDate = ref('')

// 获取当前周的日期
const getWeekDays = () => {
  const days = []
  const dayNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  
  // 获取当前日期
  const today = new Date(currentWeekStart.value)
  // 获取当前是周几（0-6，0代表周日）
  const currentDay = today.getDay()
  // 计算本周日的日期
  const sunday = new Date(today)
  sunday.setDate(today.getDate() - currentDay)
  
  // 从周日开始生成一周的日期
  for (let i = 0; i < 7; i++) {
    const date = new Date(sunday)
    date.setDate(sunday.getDate() + i)
    days.push({
      name: dayNames[date.getDay()],
      date: date.toISOString().split('T')[0]
    })
  }
  
  // 更新startDate和endDate
  startDate.value = days[0].date
  endDate.value = days[6].date
  return days
}

const weekDays = computed(() => getWeekDays())

// 格式化日期显示
const formatDate = (dateStr) => {
  const date = new Date(dateStr)
  return `${date.getMonth() + 1}月${date.getDate()}日`
}

// 格式化周范围显示
const formatWeekRange = (date) => {
  return `${new Date(startDate.value).getMonth() + 1}月${new Date(startDate.value).getDate()}日 - ${new Date(endDate.value).getMonth() + 1}月${new Date(endDate.value).getDate()}日`
}

// 获取分页数据
function getReverseData() {
  // 先更新日期范围
  getWeekDays()
  console.log('请求参数:', { startDate: startDate.value, endDate: endDate.value })
  
  // 调用后台分页接口，并传入所需参数
  getReverseList({
    startDate: startDate.value,
    endDate: endDate.value
  }).then((res) => {
    if (res.data.success == true) {
      events.value = res.data.data;
      console.log('获取到的数据:', events.value)
    }
  }).catch(error => {
    console.error('获取数据失败:', error)
  });
}

// 切换到上一周
const previousWeek = () => {
  const newDate = new Date(currentWeekStart.value)
  newDate.setDate(newDate.getDate() - 7)
  currentWeekStart.value = newDate
  // 直接调用 getReverseData，它会通过 getWeekDays 更新日期范围
  getReverseData()
}

// 切换到下一周
const nextWeek = () => {
  const newDate = new Date(currentWeekStart.value)
  newDate.setDate(newDate.getDate() + 7)
  currentWeekStart.value = newDate
  // 直接调用 getReverseData，它会通过 getWeekDays 更新日期范围
  getReverseData()
}

// 格式化小时显示
const formatHour = (hour) => {
  return `${hour.toString().padStart(2, '0')}:00`
}

// 选中的事件
const selectedEvent = ref(null)

// 显示事件详情
const showEventDetails = (event) => {
  selectedEvent.value = event
}

// 关闭事件详情
const closeEventDetails = () => {
  selectedEvent.value = null
}

// 获取特定时间段的可见日程
const getVisibleEvents = (date, hour) => {
  return events.value.filter(event => {
    if (event.date !== date) return false
    
    const startTime = event.createTime.split(' ')[1]
    const [startHour] = startTime.split(':').map(Number)
    
    // 如果是跨天的事件，需要检查结束时间
    const endTime = event.endTime.split(' ')[1]
    const [endHour] = endTime.split(':').map(Number)
    
    // 如果结束时间小于开始时间，说明跨天了
    if (endHour < startHour) {
      // 在开始日期显示开始时间，在结束日期显示结束时间
      return hour === startHour || hour === endHour
    }
    
    return hour === startHour
  })
}

// 计算事件在时间槽中的位置和高度
const getEventStyle = (event, currentHour) => {
  const startTime = event.createTime.split(' ')[1]
  const endTime = event.endTime.split(' ')[1]
  
  const [startHour, startMinute] = startTime.split(':').map(Number)
  const [endHour, endMinute] = endTime.split(':').map(Number)
  
  let startTotalMinutes = startHour * 60 + startMinute
  let endTotalMinutes = endHour * 60 + endMinute
  
  // 如果结束时间小于开始时间，说明跨天了，需要加上24小时
  if (endTotalMinutes < startTotalMinutes) {
    endTotalMinutes += 24 * 60
  }
  
  const durationMinutes = endTotalMinutes - startTotalMinutes
  
  // 计算在当前小时内的起始位置（分钟）
  const startPosition = startMinute
  
  return {
    backgroundColor: getColorByFeeling(event),
    top: `${startPosition}px`,
    height: `${durationMinutes}px`,
    position: 'absolute',
    zIndex: 1
  }
}

// 判断事件是否小于15分钟
const isShortEvent = (event) => {
  const startTime = event.createTime.split(' ')[1]
  const endTime = event.endTime.split(' ')[1]
  
  const [startHour, startMinute] = startTime.split(':').map(Number)
  const [endHour, endMinute] = endTime.split(':').map(Number)
  
  let startTotalMinutes = startHour * 60 + startMinute
  let endTotalMinutes = endHour * 60 + endMinute
  
  // 如果结束时间小于开始时间，说明跨天了，需要加上24小时
  if (endTotalMinutes < startTotalMinutes) {
    endTotalMinutes += 24 * 60
  }
  
  const durationMinutes = endTotalMinutes - startTotalMinutes
  
  return durationMinutes < 15
}

// 计算事件持续时间
const calculateDuration = (event) => {
  const startTime = event.createTime.split(' ')[1]
  const endTime = event.endTime.split(' ')[1]
  
  const [startHour, startMinute] = startTime.split(':').map(Number)
  const [endHour, endMinute] = endTime.split(':').map(Number)
  
  let startTotalMinutes = startHour * 60 + startMinute
  let endTotalMinutes = endHour * 60 + endMinute
  
  // 如果结束时间小于开始时间，说明跨天了，需要加上24小时
  if (endTotalMinutes < startTotalMinutes) {
    endTotalMinutes += 24 * 60
  }
  
  const durationMinutes = endTotalMinutes - startTotalMinutes
  
  const hours = Math.floor(durationMinutes / 60)
  const minutes = durationMinutes % 60
  
  if (hours === 0) {
    return `${minutes}分钟`
  } else if (minutes === 0) {
    return `${hours}小时`
  } else {
    return `${hours}小时${minutes}分钟`
  }
}

// 根据tagId值获取颜色
const getColorByFeeling = (event) => {
  // 如果是睡觉事件，统一使用淡紫色
  if (event.scheduleName === '睡觉') {
    return '#B39DDB' // 淡紫色
  }
  
  const colorMap = {
    1: '#00E676', // 亮绿色
    3: '#B39DDB', // 淡紫色
    4: '#B39DDB', // 淡紫色
    6: '#2196F3', // 蓝色
    7: '#2196F3', // 蓝色
    8: '#FFC107', // 黄色
    5: '#FF9800', // 橙色
    2: '#ff4d4d'  // 红色
  }
  return colorMap[event.tagId] || '#9E9E9E' // 默认灰色
}

// 模拟日程数据
const events = ref([
    // 周日
    {
    id: 1,
    scheduleName: '晨跑',
    date: new Date(new Date().setDate(new Date().getDate() - new Date().getDay())).toISOString().split('T')[
            0
        ],
    createTime: '06: 40',
    endTime: '07: 00',
    feeling: 4,
    description: '晨跑30分钟，保持健康的生活方式。'
    }
])

// 初始化时获取数据
getReverseData()

// 格式化时间显示
const formatTimeDisplay = (timeStr) => {
  // 从 "2025-05-25 20:45" 提取 "20:45"
  return timeStr.split(' ')[1]
}
</script>

<style scoped>
.weekly-calendar {
  width: 100%;
  height: 100%;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
}

.calendar-controls {
  padding: 16px 24px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e0e0e0;
}

.week-navigation {
  display: flex;
  align-items: center;
  justify-content: space-between;
  max-width: 400px;
  margin: 0 auto;
  background: white;
  padding: 8px 16px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.nav-btn {
  padding: 8px 12px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  background-color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
  transition: all 0.2s ease;
  font-size: 14px;
  color: #333;
  min-width: 80px;
  justify-content: center;
  white-space: nowrap;
}

.nav-btn:hover {
  background-color: #f0f0f0;
  border-color: #d0d0d0;
  transform: translateY(-1px);
}

.arrow {
  font-size: 16px;
  line-height: 1;
  display: inline-block;
  width: 16px;
  text-align: center;
}

.current-week {
  font-size: 15px;
  font-weight: 500;
  color: #333;
  padding: 0 16px;
  text-align: center;
  min-width: 160px;
  white-space: nowrap;
}

.calendar-header {
  display: flex;
  background-color: #f5f5f5;
  border-bottom: 1px solid #e0e0e0;
}

.time-column {
  width: 60px;
  flex-shrink: 0;
  border-right: 1px solid #e0e0e0;
}

.day-column {
  flex: 1;
  min-width: 120px;
  border-right: 1px solid #e0e0e0;
}

.day-column:last-child {
  border-right: none;
}

.day-header {
  padding: 10px;
  text-align: center;
  border-left: 1px solid #e0e0e0;
}

.day-name {
  font-weight: bold;
  margin-bottom: 4px;
}

.day-date {
  font-size: 0.9em;
  color: #666;
}

.calendar-body {
  display: flex;
  height: calc(100% - 80px);
}

.time-slots {
  width: 60px;
  flex-shrink: 0;
  border-right: 1px solid #e0e0e0;
}

.days-grid {
  display: flex;
  flex: 1;
  overflow-x: auto;
  position: relative; /* 确保事件块定位正确 */
}

.time-slot {
  height: 60px;
  border-bottom: 1px solid #e0e0e0;
  position: relative;
  overflow: visible; /* 允许事件块超出时间槽 */
}

.time-slot:nth-child(1) {
  border-top: 1px solid #e0e0e0;
}

.time-slot:last-child {
  border-bottom: none;
}

.time-slot .time-label {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.8em;
  color: #666;
  background-color: #fafafa;
  border-right: 1px solid #e0e0e0;
  text-align: center;
  line-height: 60px;
  box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.8); /* 添加内部白色描边 */
}

.time-slot:last-child .time-label {
  border-bottom: none;
}

.time-slot .time-label:last-child {
  border-right: none;
}

.event {
  position: absolute;
  left: 0;
  right: 0;
  padding: 4px;
  color: white;
  font-size: 0.9em;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  z-index: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  border-bottom: 2px solid rgba(255, 255, 255, 0.3); /* 使用白色半透明边框 */
  border-right: 2px solid rgba(255, 255, 255, 0.3); /* 使用白色半透明边框 */
  cursor: pointer;
  transition: transform 0.2s ease;
}

.event:last-child {
  border-right: none;
}

.event:hover {
  transform: scale(1.02);
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.modal-header {
  padding: 20px;
  color: white;
  border-radius: 8px 8px 0 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h2 {
  margin: 0;
  font-size: 1.5em;
}

.close-btn {
  background: none;
  border: none;
  color: white;
  font-size: 24px;
  cursor: pointer;
  padding: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.2s;
}

.close-btn:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.modal-body {
  padding: 20px;
}

.event-info {
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  color: #666;
  font-size: 14px;
}

.info-item span {
  line-height: 24px;
  color: #333;
  font-weight: 500;
}

.icon {
  margin-right: 12px;
  font-size: 1.2em;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  line-height: 1;
  color: #666;
}

.event-description {
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.event-description h3 {
  margin: 0 0 12px 0;
  color: #333;
  font-size: 1.1em;
}

.event-description p {
  margin: 0;
  color: #666;
  line-height: 1.6;
}

/* 弹窗动画 */
.modal-enter-active,
.modal-leave-active {
  transition: opacity 0.3s ease;
}

.modal-enter-from,
.modal-leave-to {
  opacity: 0;
}

.modal-enter-active .modal-content,
.modal-leave-active .modal-content {
  transition: transform 0.3s ease;
}

.modal-enter-from .modal-content,
.modal-leave-to .modal-content {
  transform: scale(0.9);
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  .calendar-controls {
    padding: 12px 16px;
  }

  .week-navigation {
    padding: 6px 12px;
  }

  .nav-btn {
    padding: 6px 10px;
    min-width: 70px;
    font-size: 13px;
    gap: 3px;
  }

  .arrow {
    font-size: 14px;
    width: 14px;
  }

  .current-week {
    font-size: 13px;
    padding: 0 10px;
    min-width: 140px;
  }

  .time-column {
    width: 50px;
  }

  .day-column {
    min-width: 100px;
  }

  .day-header {
    padding: 8px 4px;
  }

  .day-name {
    font-size: 13px;
  }

  .day-date {
    font-size: 12px;
  }

  .time-slot .time-label {
    font-size: 11px;
  }

  /* 弹窗在移动端的优化 */
  .modal-content {
    width: 95%;
    margin: 10px;
  }

  .modal-header {
    padding: 16px;
  }

  .modal-header h2 {
    font-size: 1.2em;
  }

  .modal-body {
    padding: 16px;
  }

  .info-item {
    font-size: 13px;
    margin-bottom: 12px;
  }

  .event-description h3 {
    font-size: 1em;
  }

  .event-description p {
    font-size: 13px;
  }
}

/* 超小屏幕适配 */
@media screen and (max-width: 480px) {
  .calendar-controls {
    padding: 8px 12px;
  }

  .week-navigation {
    padding: 4px 8px;
  }

  .nav-btn {
    padding: 4px 8px;
    min-width: 60px;
    font-size: 12px;
    gap: 2px;
  }

  .arrow {
    font-size: 12px;
    width: 12px;
  }

  .current-week {
    font-size: 12px;
    padding: 0 8px;
    min-width: 120px;
  }

  .time-column {
    width: 40px;
  }

  .day-column {
    min-width: 80px;
  }

  .day-header {
    padding: 6px 2px;
  }

  .day-name {
    font-size: 12px;
  }

  .day-date {
    font-size: 11px;
  }

  .time-slot .time-label {
    font-size: 10px;
  }

  .event {
    font-size: 10px;
    padding: 1px 3px;
  }
}
</style>
